package cn.yuanqiao.activiti.config;


import cn.yuanqiao.activiti.listener.GlobalEventListener;
import cn.yuanqiao.common.config.YqDatabaseIdProvider;
import cn.yuanqiao.common.enums.DbIdEnum;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Arrays;

import static org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl.*;
import static org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl.DATABASE_TYPE_ORACLE;

/**
 * @ClassName: ActivitiConfig
 * @Description: 类的描述
 * @author: lihuahua
 * @date: 2023/5/19 15:10
 * @Blog: huahuacoco.top
 */

@Configuration
public class ActivitiConfig {

    @Resource
    PlatformTransactionManager transactionManager;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    GlobalEventListener globalEventListener;

    @Resource
    private YqDatabaseIdProvider yqDatabaseIdProvider;


    @Bean
    public SpringProcessEngineConfiguration getProcessEngineConfiguration() {
        DataSource dataSource = applicationContext.getBean(DataSource.class);
        //金仓专用
        //DataSource dataSource = activitiDataSource.getDataSource();
        SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();
        config.setDataSource(dataSource);
        config.setTransactionManager(transactionManager);
        config.setEventListeners(Arrays.asList(globalTaskListener()));
        String databaseId =  yqDatabaseIdProvider.getDatabaseId();
        if(DbIdEnum.DM.getCode().equalsIgnoreCase(databaseId)){//流程适配达梦数据库
            config.setDatabaseType(DATABASE_TYPE_MYSQL);
        }else{
            config.setDatabaseType(DATABASE_TYPE_ORACLE);
        }


        //初始化工作流数据库用
        config.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
        return config;
    }

    private ActivitiEventListener globalTaskListener() {
        return globalEventListener;
    }

}